package org.example.spring.aop.annotation;


import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Order(5)
@Aspect
@Component
public class RetryAspect {
    private static final Logger log= LoggerFactory.getLogger(RetryAspect.class);

    @Pointcut("@annotation(org.example.spring.aop.annotation.Retry)")
    public void retryAnnotation() {
    }

    @Around("retryAnnotation()")
    public Object retry(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Retry retry = method.getAnnotation(Retry.class);
        String methodName = method.getName();
        System.out.println("方法名称" + methodName);
        int times = retry.maxAttempts();
        if(times<=0){
            times=1;
        }
        for (;times>=0;times--){
            try {
                return joinPoint.proceed();
            } catch (Throwable e) {
                System.out.println("方法" + methodName + "执行失败, 剩余重试次数" + times);
                if(times == 0){
                    throw e;
                }
                System.out.println("开始重试");
            }
        }
        return new Object();
    }
}
